import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori, association_rules
import openpyxl

df = pd.read_excel('merged_table.xlsx')

df['ordertime'] = pd.to_datetime(df['ordertime'])

mid_obj = df.groupby('orderid').apply(lambda x: x['id'].tolist())
mid_obj.to_csv('mid_obj.csv', index=False)
mid_obj = mid_obj.to_list()

te = TransactionEncoder()
te_ary = te.fit(mid_obj).transform(mid_obj)
df_trans = pd.DataFrame(te_ary, columns=te.columns_)

frequent_itemsets = apriori(df_trans, min_support=0.01, use_colnames=True)

rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.5)

rules.to_csv('association_rules.csv', index=False)

rules_df = pd.read_csv('association_rules.csv')

# 排序
sorted_df = rules_df.sort_values(by="support", ascending=False)

# 输出support——id文件
sorted_df.to_csv('sorted_df.csv', index=False)

# 选取列antecedents support
select_columns = ['antecedents', 'support']
results = sorted_df[select_columns]

results.to_csv('results.csv', index=False)
